package com.hooview.api.controller;

import com.github.pagehelper.Page;
import com.google.common.collect.Lists;
import com.hooview.api.dto.ProfitRecordDTO;
import com.hooview.api.entity.DailyCount;
import com.hooview.api.entity.HyProfit;
import com.hooview.api.entity.ProfitRecord;
import com.hooview.api.entity.User;
import com.hooview.api.service.*;
import com.hooview.common.utils.AjaxMsg;
import com.hooview.common.utils.ValidUtil;
import com.hooview.contants.Constants;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.swing.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

@RestController
@RequestMapping("/api/profit")
public class ProfitRecordController {
    @Autowired
    private ProfitRecordService profitRecordService;
    @Autowired
    private NewsService newsService;
    @Autowired
    private UserService userService;
    @Autowired
    private DailyCountService dailyCountService;
    @Autowired
    private HyProfitService hyProfitService;
    /**
     * 用户所有收益记录及获利次数
     *分页
     * @param uid
     * @return
     */
    @RequestMapping(value = "/profitRecordList", method = RequestMethod.GET)
    @ResponseBody
    public AjaxMsg profitRecordList(String uid,@RequestParam(defaultValue = "1") Integer pageNum,@RequestParam(defaultValue = "10") Integer pageSize) {
//        User entity = ShiroUtils.getUserEntity();
        List<ProfitRecord> profitRecords = profitRecordService.queryByUser(uid, pageNum, pageSize);
        Map map = new HashMap();
        Integer count = profitRecordService.countByUser(uid);
        map.put("count",count);
        if(profitRecords == null){
            map.put("profis",null);
            return new AjaxMsg(map);
        }

        List<ProfitRecordDTO> profits = Lists.newArrayList();
        for (ProfitRecord p: profitRecords) {
            ProfitRecordDTO profitRecordDTO = new ProfitRecordDTO(p);
            User user = userService.queryById(uid);
            profitRecordDTO.setAvatar(user.getAvatar());
            if(StringUtils.isNotBlank(p.getRefereId())){
                //查找由谁获得
                User refere = userService.queryById(p.getRefereId());
                if(refere.getReferee().equals(uid)) {
                    profitRecordDTO.setAvatar_1(refere.getAvatar());
                    profitRecordDTO.setDisplayName(user.getDisplayName());
                    profitRecordDTO.setDisplayName_1(refere.getDisplayName());
                }else{
                    profitRecordDTO.setAvatar_2(refere.getAvatar());
                    profitRecordDTO.setDisplayName_2(refere.getDisplayName());
                    String avatar_1 = userService.queryById(refere.getReferee()).getAvatar();
                    profitRecordDTO.setAvatar_1(avatar_1);
                    profitRecordDTO.setDisplayName_1(userService.queryById(refere.getReferee()).getDisplayName());
                }
            }
            profits.add(profitRecordDTO);
        }
        map.put("profis",profits);
        return new AjaxMsg(map);
    }

    /**
     * 用户当天收益总量
     * @param uid
     * @return
     */
    @RequestMapping(value = "/profitToday", method = RequestMethod.GET)
    @ResponseBody
    public AjaxMsg profitToday(String uid){
        Float integer = profitRecordService.profitToday(uid);
        return new AjaxMsg(integer);
    }

    @RequestMapping(value = "/sum",method = RequestMethod.GET)
    @ResponseBody
    public AjaxMsg sum(String uid){
        Double sum = profitRecordService.profitSum(uid);
        return new AjaxMsg(sum);
    }

    /**
     * 快讯分享后糖果领取 [废弃]
     * @param newsId
     * @param uid
     * @return
     */
//    @RequestMapping(value = "/share",method = RequestMethod.GET)
//    @ResponseBody
//    public AjaxMsg share(Integer newsId,String uid){
//        if(ValidUtil.isEmpty(newsId,uid))
//            return new AjaxMsg(AjaxMsg.FAILURE,"参数不能为空");
//        News news = newsService.selectByPrimaryKey(newsId);
//        if(null == news)
//            return new AjaxMsg(AjaxMsg.FAILURE,"分享快讯不存在！");
//        ProfitRecord profitRecord = profitRecordService.findByUserAndNewsId(uid,newsId);
//        if(profitRecord != null )
//            return new AjaxMsg(AjaxMsg.FAILURE,"该快讯已经分享过！");
//        if(news.getCandy() <= 0)
//            return new AjaxMsg(AjaxMsg.FAILURE,"糖果已经分享完!");
//        Date createTime = news.getCreateTime();
//        Calendar instance = Calendar.getInstance();
//        instance.setTime(createTime);
//        instance.add(Calendar.HOUR_OF_DAY,news.getExpireTime()/3600);
//        if(new Date().after(instance.getTime()))
//            return new AjaxMsg(AjaxMsg.FAILURE,"分享快讯已过期!");
//        User user = userService.queryById(uid);
//        if(user == null)
//            return new AjaxMsg(AjaxMsg.FAILURE,"账号不存在！");
//        User refere_1 = null;
//        User refere_2 = null;
//        if(StringUtils.isNotBlank(user.getReferee()))
//            refere_1 = userService.queryById(user.getReferee());
//        if(refere_1 != null && StringUtils.isNotBlank(refere_1.getReferee()))
//            refere_2 = userService.queryById(refere_1.getReferee());
//        //随机生成糖果
//        Double coin = randomCoin();
//        while(news.getCandy()<coin){
//            coin = randomCoin();
//        }
//        news.setCandy((int) (news.getCandy() - coin));
//        newsService.updateByPrimaryKeySelective(news);
//        save(uid,coin,ProfitType.SHARE.getValue(),newsId,null);
//        //关联人
//        if(refere_1 != null)
//            save(refere_1.getId(),coin*0.2, ProfitType.SHARE_1.getValue(),newsId,uid);
//        if(refere_2 != null)
//            save(refere_2.getId(),coin*0.1, ProfitType.SHARE_2.getValue(),newsId,uid);
//        return new AjaxMsg(coin);
//    }

    /**
     * 获取阅读 分享 收益
     *
     * @param uid
     * @param type
     * @return
     */
    @RequestMapping(value = "/getProfit",method = RequestMethod.GET)
    public AjaxMsg getProfit(String uid,String type,Integer newsId){
        if(ValidUtil.isEmpty(uid,type,newsId))
            return new AjaxMsg("500","请求必要参数不能为空！");
        if(userService.queryById(uid) == null || newsService.selectByPrimaryKey(newsId) == null)
            return new AjaxMsg("500","用户或文章不存在！");

        DailyCount dailyCount = dailyCountService.selectToday(uid);
        if(dailyCount != null){
            if(Constants.PROFIT_READ.equals(type) && dailyCount.getReadAmount() >= 8){
                return new AjaxMsg("500","今日已达到最大阅读量,无法继续获得收益!");
            }else if(Constants.PROFIT_SHARE_ARTICLE.equals(type) && dailyCount.getShareArticleAmount() >= 5){
                return new AjaxMsg("500","今日分享文章已达到最大数量，无法继续获得收益!");
            } else if (Constants.PROFIT_SHARE_NEWS.equals(type) && dailyCount.getShareNewsAmount() >= 5){
                return new AjaxMsg("500","今日分享快讯已达到最大数量，无法继续获得收益!");
            }
        }
        if(Constants.PROFIT_READ.equals(type)){
            ProfitRecord profitRecord = profitRecordService.findByUserAndNewsIdAndType(uid, newsId,Constants.PROFIT_READ);
            if(profitRecord != null)
                return new AjaxMsg("500","奖励已领取!");
        }
        if(Constants.PROFIT_SHARE_NEWS.equals(type)){
            ProfitRecord profitRecord = profitRecordService.findByUserAndNewsIdAndType(uid, newsId,Constants.PROFIT_SHARE_NEWS);
            if(profitRecord != null)
                return new AjaxMsg();
        }
        if(Constants.PROFIT_SHARE_ARTICLE.equals(type)){
            ProfitRecord profitRecord = profitRecordService.findByUserAndNewsIdAndType(uid, newsId,Constants.PROFIT_SHARE_ARTICLE);
            if(profitRecord != null)
                return new AjaxMsg();
        }
        Double profit = profitRecordService.getProfit(uid, type,newsId);
        return new AjaxMsg(profit);
    }

    /**
     * HY收益记录
     * @param uid
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping(value = "/hyProfitHistory",method = RequestMethod.POST)
    public  AjaxMsg hyProfitHistory(String uid,@RequestParam(defaultValue = "1") Integer pageNum,@RequestParam(defaultValue = "10") Integer pageSize){
        Page<HyProfit> page = hyProfitService.selectByUser(uid,pageNum,pageSize);
        return new AjaxMsg(page);
    }

    private void save(String uid,Double num,String type,Integer newsId,String refereId){
        ProfitRecord profitRecord = new ProfitRecord();
        profitRecord.setNum(num);
        profitRecord.setUid(uid);
        profitRecord.setType(type);
        profitRecord.setNewsId(newsId);
        profitRecord.setRefereId(refereId);
        profitRecordService.save(profitRecord);
    }

    //生成随机糖果
    private Double randomCoin(){
        Random random = new Random();
        double p1=0.7; //1~10的概率
        double p=(((int)random.nextInt(10)%10+1)*1.0/10 < p1)?p1:(1-p1); //实际所取概率
        int max=(p==p1)?10:20;
        int num=(int)random.nextInt(max)%(max)+1;
        return Double.valueOf(num);
    }



}
